const WebSocket = require('ws');
const express = require('express');
const multer = require('multer');
const fs = require('fs');
const path = require('path');
const cors = require('cors');

const app = express();
const PORT = 3001;
const upload = multer({ dest: 'uploads/' });

app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));

// 初始化消息存储
if (!fs.existsSync('messages.json')) {
  fs.writeFileSync('messages.json', '[]');
}

const server = app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

const wss = new WebSocket.Server({ server });
const messages = JSON.parse(fs.readFileSync('messages.json', 'utf8'));

// 心跳检测间隔(毫秒)
const HEARTBEAT_INTERVAL = 25000;

wss.on('connection', (ws) => {
  ws.isAlive = true;
  ws.send(JSON.stringify({ type: 'INIT', data: messages.slice(-50) }));

  // 设置心跳检测定时器
  const heartbeatInterval = setInterval(() => {
    if (ws.isAlive === false) {
      return ws.terminate();
    }
    ws.isAlive = false;
    ws.send(JSON.stringify({ type: 'PING' }));
  }, HEARTBEAT_INTERVAL);

  ws.on('message', (rawData) => {
    const message = JSON.parse(rawData);
    console.log(message);

    // 处理心跳消息
    if (message.type === 'PING') {
      ws.send(JSON.stringify({ type: 'PONG' }));
      return;
    }
    if (message.type === 'PONG') {
      ws.isAlive = true;
      return;
    }

    // 处理普通消息
    messages.push(message);
    fs.writeFileSync('messages.json', JSON.stringify(messages));
    wss.clients.forEach(client => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(JSON.stringify({ type: 'NEW_MESSAGE', data: message }));
      }
    });
  });

  ws.on('close', () => {
    clearInterval(heartbeatInterval);
  });
});

app.post('/upload', upload.single('file'), (req, res) => {
  const ext = path.extname(req.file.originalname);
  const newPath = `${req.file.path}${ext}`;
  fs.renameSync(req.file.path, newPath);
  res.json({
    url: `/uploads/${path.basename(newPath)}`,
    originalName: req.file.originalname
  });
});

app.use('/uploads', express.static('uploads'));
